package com.ss.service.support;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ss.core.exceptions.SummerExecuteException;
import com.ss.entity.SummerFlow;
import com.ss.mapper.SummerFlowMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author: 夏十七
 * @Date: 2019/7/28 17:38
 * @Version 1.0
 */
@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class ExecuteFlow {

    @Autowired
    @SuppressWarnings("all")
    private SummerFlowMapper summerFlowMapper;

    /**
     * 获取可用的Flow
     * @param apiPath 凭证
     * @return
     */
    public SummerFlow getUseFlow(String apiPath){
        //检测审批流是否存在
        QueryWrapper<SummerFlow> query = Wrappers.query();
        query.eq("api_path",apiPath);
        SummerFlow summerFlow = summerFlowMapper.selectOne(query);
        if (summerFlow==null){
            throw new SummerExecuteException(apiPath + "事件流不存在, The flow not exist!");
        }
        if (!summerFlow.getIsUse()){
            throw new SummerExecuteException(summerFlow.getName()+"事件流已被停用,The flow stop using!");
        }
        return summerFlow;
    }

    /**
     *  获取可用的Flow，支持跨节点
     * @param apiPath 凭证
     * @return
     */
    public SummerFlow getCrossNodeFlow(String apiPath){
        SummerFlow flow = this.getUseFlow(apiPath);
        if (!flow.getIsCrossNode()){
            throw new SummerExecuteException(flow.getName()+"事件流不支持跨节点!");
        }
        return flow;
    }


    /**
     *  获取可用的Flow，支持指定审核人
     * @param apiPath 凭证
     * @return
     */
    public SummerFlow getAppointMemberFlow(String apiPath){
        SummerFlow flow = this.getUseFlow(apiPath);
        if (!flow.getIsAppointMember()){
            throw new SummerExecuteException(flow.getName()+"事件流不支持指定审核人!");
        }
        return flow;
    }


    /**
     *  获取可用的Flow，支持跨节点，指定审核人
     * @param apiPath 凭证
     * @return
     */
    public SummerFlow getAppointMemberAndCrossNodeFlow(String apiPath){
        SummerFlow flow = this.getCrossNodeFlow(apiPath);
        if (!flow.getIsAppointMember()){
            throw new SummerExecuteException(flow.getName()+"事件流不支持指定审核人!");
        }
        return flow;
    }




}
